#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Image.h"
#include <QMenuBar>
#include <QFileDialog>
#include <QString>
#include <string>
#include <QDebug>
#include <QPainter>
#include <QPaintDevice>
#include <QPaintEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    img=new Image;
    isFileOpen=false;

    //菜单栏
    QMenuBar * mBar = menuBar();
    setMenuBar(mBar);

    QMenu *fileMenu = mBar->addMenu("File");
    QMenu *funcMenu = mBar->addMenu("Func");

    QAction *openFile = fileMenu->addAction("open file");
    QAction *saveFile = fileMenu->addAction("save file");

     QAction *flipFunc = funcMenu->addAction("Flip");
     QAction *rotateFunc = funcMenu->addAction("Rotate");
     QAction *cropFunc = funcMenu->addAction("Crop");
     QAction *grayFunc = funcMenu->addAction("Gray");

    //打开文件的连接
    connect(openFile,&QAction::triggered,[=](){
       QString filePath = QFileDialog::getOpenFileName(this,"open file");

       std::cout<<filePath.toStdString()<<std::endl;


       if(img->ReadBmp(filePath.toStdString())){
           qDebug()<<"read success!";
           if(img==nullptr){
               qDebug()<<"img is nullptr!\n";
           }else{

            //img->DatePrint();
            isFileOpen = true;
            update();
           }
       }

    });

    //保存文件的连接
    connect(saveFile,&QAction::triggered,[=](){
       QString savePath = QFileDialog::getSaveFileName(this,"save file");
       img->WriteBmp(savePath.toStdString());
    });

    connect(flipFunc,&QAction::triggered,[=](){
        if(isFileOpen){
            img->Flip(1);
            update();
        }else{
            qDebug()<<"file is not opened!\n";
            //弹出警告框
        }
    });

    connect(rotateFunc,&QAction::triggered,[=](){
        if(isFileOpen){
            img->Rotate(90);
            update();
        }else{
            qDebug()<<"file is not opened!\n";
            //弹出警告框
        }
    });

    connect(cropFunc,&QAction::triggered,[=](){
        if(isFileOpen){
            img->Crop(0,0,img->getHeight()/2,img->getWidth()/2);
            update();
        }else{
            qDebug()<<"file is not opened!\n";
            //弹出警告框
        }
    });

    connect(grayFunc,&QAction::triggered,[=](){
        if(isFileOpen){
            img->Gray();
            update();
        }else{
            qDebug()<<"file is not opened!\n";
            //弹出警告框

        }
    });

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent*){
    if(isFileOpen){
        QPainter painter(this);
        QRect target(200,100,400,400);//初设需要修改
        painter.drawImage(target,this->img->ToQImage());
    }
}
